package com.mars.diancan.aop;

import com.mars.diancan.constant.CookieConstant;
import com.mars.diancan.constant.RedisConstant;
import com.mars.diancan.exception.DiancanAuthorizeException;
import com.mars.diancan.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 卖家授权 aop验证
 *  1.通过aop切面，获取用户登录的token:
 *    -- 创建切面类：@Aspect/@Compnent
 *    -- 切面方法：切点@Ponitcut()
 *    -- 切面方法：要执行切点的时机和方法实现:@Before
 *  2.未获取到，抛出自定义的 DiancanAuthorizeException 异常：
 *    --  需创建DiancanAuthorizeException异常，继承 RunTimeException
 *  3.创建handler包，创建全局捕获异常的类：
 *    -- 类前添加 @ControllerAdvice
 *    -- 方法前，设置拦截异常的名字
 * @author MARS
 * @date 2018/7/11
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     *
     * 设置切入点
     */
    @Pointcut("execution(public * com.mars.diancan.controller.Seller*.*(..))" +
            " && !execution(public * com.mars.diancan.controller.SellerUserController.*(..))")
    public void vertify(){}

    /**
     * 在具体切入点之前进行切入
     */
    @Before("vertify()")
    public void doVertify() {
        // 获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie == null) {
            log.warn("登陆校验，cookie中查不到token");
            throw new DiancanAuthorizeException();
        }

        // 去redis中查询
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)){
            log.warn("登陆校验，redis中查不到token");
            throw new DiancanAuthorizeException();
        }
    }
}
